<template>
<!--	<up-popup mode="right" :customStyle="{width: '100vw'}" :show="show">-->
		<up-navbar title="选择要删除的人" :autoBack="false" placeholder @leftClick="close"></up-navbar>
		<!-- 搜索 -->
		<view style="margin:  0 24rpx; background-color: #fff;">
			<up-search @search="reloadList" @clear="reloadList" :showAction="false" clearabled placeholder="搜索" v-model="keyword" shape="square"></up-search>
		</view>
		<view class="list-box">
			<!-- 列表 -->
			<up-list height="77vh">
				<mescroll-uni ref="mescrollRef" :top="listHeightStyle.top" bottom="120rpx" @init="mescrollInit" @up="upCallback">
					<up-list-item v-for="item in userList" :key="item.id" style="padding: 0 20rpx;">
						<view class="list-item" @click="removeAndAdd(item)">
							<view class="check">
								<up-checkbox usedAlone :checked="setChecked(item)" @change="removeAndAdd(item)"></up-checkbox>
							</view>
							<view class="img" style="width: 72rpx; height: 72rpx;">
								<up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
									<template #error>
										<text>{{showUserName(item.username)}}</text>
									</template>
								</up-image>
							</view>
							<view>
								{{item.username}} {{item.username_en}}
							</view>
						</view>
					</up-list-item>
				</mescroll-uni>
			</up-list>
		</view>


		<!-- 底部选中 -->
		<view class="select-container">
			<view class="select-left">
				<text>已选择（{{selection?.length}}）:</text>
			</view>
			<scroll-view class="scrollContainer" scroll-x>
				<view style="display: flex; width: 100%;" @click="selectedShow = true">
					<view v-for="item in selection" :key="item.id" class="select-item">
						<up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
							<template #error>
								<text>{{showUserName(item.username)}}</text>
							</template>
						</up-image>
					</view>
				</view>
			</scroll-view>
			<view class="select-right">
				<up-button @click="submit" :customStyle="{border: 'none', width: '102rpx', height: '52rpx'}" :disabled="selection?.length == 0" type="primary" text="确定"></up-button>
			</view>
		</view>


		<!-- 移除弹出框 -->
		<up-popup :show="selectedShow" @close="selectedShow = fasle">
			<view class="popup-header">
				<view @click="selectedShow = false">
					<up-icon :size="18" bold name="close"></up-icon>
				</view>
				<view style="font-weight: 500;">已选择({{selection?.length}})</view>
				<view @click="selectedShow = false">确定</view>
			</view>
			<view class="popup-content">
				<up-list height="600rpx">
					<up-list-item v-for="item in selection" :key="item.id" style="padding: 0 20rpx;">
						<view class="list-item" @click="removeAndAdd(item)">
							<view class="check">
								<up-checkbox usedAlone :checked="setChecked(item)"></up-checkbox>
							</view>
							<view class="img" style="width: 64rpx; height: 64rpx;">
								<up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
									<template #error>
										<text>{{showUserName(item.username)}}</text>
									</template>
								</up-image>
							</view>
							<view>
								{{item.username}} {{item.username_en}}
							</view>
							<view class="del">
								<up-button type="primary" size="mini" :hairline="false" @click="removeAndAdd(item)" text="移除"></up-button>
							</view>
						</view>
					</up-list-item>
				</up-list>
			</view>
		</up-popup>

<!--	</up-popup>-->
</template>

<script>
import { getCurrentInstance } from "vue";
import { chatApi } from '@/apis/cloud/chat'
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
const AvaterBaseUrl = "https://cloud.mfarmers.com/dist/interface/public/upload/avatar/";
export default {
  name: "GroupMemberPicker",
	props: {
		// userInfo: {
		// 	type: Object
		// }
	},
	mixins: [MescrollMixin],
	data() {
		return {
			upOption: {
				page: {
					size: 20 // 每页数据的数量,默认10
				},
				noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
				empty: {
					tip: '已经到底了'
				}
			},
			show: false,
			selectedShow: false,
			currentData: [],
			selection: [],
			userList: [],
			originList: [],
			pageSize: 20,
			pageNum: 1,
			total: 0,
			keyword: '',
			userInfo: {},
			source:'',
			listHeight: 0, // 动态计算的高度
			listHeightStyle: {}, // 动态计算的样式
			topHeight: 0,
			andaddpersonnel:null
		};
	},
  onLoad(value) {

  },
  // 页面销毁前
  onUnload(){

  },
  created(){
    let that = this
    const instance = getCurrentInstance().proxy;
    const eventChannel = instance.getOpenerEventChannel();
    eventChannel.on('groupchatremove', async function(data) {
      uni.showLoading({
        title: '加载中....'
      });
	  const imgheadList = JSON?.parse(data?.imgheadList) || []
	  that.originList = imgheadList.filter(item => item.group_role !== 98 && item.group_role !== 99)
      that.userList = uni.$u.deepClone(that.originList)
      that.userInfo = JSON?.parse(data.userInfo)
      that.source = data.source
      //that.getList();
      uni.hideLoading()
    })
    this.calculateListHeight()
  },
	mounted() {

	},
	methods: {
    calculateListHeight() {
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        top:'220rpx'
      };
      // #endif

      // #ifdef H5
      this.listHeightStyle = {
        top:'155rpx'
      };
      // #endif
    },
		mescrollInit(mescroll) {
			this.mescroll = mescroll;
		},
		/*上拉加载的回调*/
		upCallback(page) {
			this.mescroll.endByPage(this.userList.length,this.userList.length);return;
			this.pageNum = page.num; // 页码, 默认从1开始
			this.pageSize = page.size; // 页码, 默认从1开始
			this.getList();
		},
		/*若希望重新加载列表,只需调用此方法即可(内部会自动page.num=1,再主动触发up.callback)*/
		reloadList(){
			this.userList = []
			if (!this.keyword.trim()) return this.userList = uni.$u.deepClone(this.originList)
			const regex = new RegExp(this.keyword, 'i');
			const tmpList = this.originList.filter(item => 
				regex.test(item.username || '')
			)
			this.userList =  uni.$u.deepClone(tmpList)
			//this.mescroll.resetUpScroll();
		},
		open(data) {
			this.show = true;
			this.selection = JSON.parse(data);
      		this.getList();
		},
		close() {
      		uni.navigateBack();
		},
		submit() {
			uni.navigateBack();
			if(this.source == "CreateGroup"){
				uni.$emit('CreateGroupMemberPicker',JSON.stringify(this.selection))
			}else if(this.source == "groupchat"){
				uni.$emit('groupchatMemberPicker',JSON.stringify(this.selection))
			}else if(this.source == "groupchatremove"){
				uni.$emit('groupchatRemoveMemberPicker',JSON.stringify(this.selection))
			}
			// this.$emit('ok', JSON.stringify(this.selection));
			// this.show = false;
		},
		setUserImg(item) {
			return AvaterBaseUrl+item.phone+'.jpg'
		},
		// 名称超长处理
		showUserName(username) {
			if (username && username.length > 2) {
				return username.substr(1, 2);
			} else {
				return username;
			}
		},
		// 是否选中
		setChecked(event) {
			const findIndex = this.selection?.findIndex(item => item.id == event.id)
			if(findIndex != -1) {
				return true
			}else {
				return false
			}
		},
		// 移除
		removeAndAdd(item) {
			const findIndex = this.selection.findIndex(i => item.id == i.id);
			if (findIndex != -1) {
				this.selection.splice(findIndex, 1);
			} else {
				this.selection.push(item);
			}
		},
		// 用户列表
		async getList() {
			return;
      let token = uni.getStorageSync('token')
			// composition上拉加载  compositionupdate下拉刷新
			const params = {
				'data[keywords]': this.keyword,
				'data[pageSize]': this.pageSize,
				'data[page]': this.pageNum,
				url: 'index.php/users/Member/getList'
			}

			const msg = await chatApi(this?.userInfo?.token || token, params);

			if(msg.code === 200) {
				if(this.pageNum === 1) {
					this.userList = msg.data.data;
				}else {
					msg.data.data.forEach(item => {
						this.userList.push(item)
					})
				}
				this.total = msg.data.total;

				this.mescroll.endByPage(msg.data.data.length, msg.data.total);
			}else {
				this.mescroll.endErr()
			}

		},
	}
};
</script>

<style lang="scss" scoped>
.list-item {
	position: relative;
	display: flex;
	align-items: center;
	padding: 20rpx;
	border-bottom: 0.5px solid #ddd;
	.check {
		margin-right: 10rpx;
	}
	.img {
		margin-right: 24rpx;
		text {
			display: inline-block;
			width: 100%;
			height: 100;
			border-radius: 10rpx;
			color: #fff;
			font-size: 26rpx;
			text-align: center;
			line-height: 72rpx;
			background-color: #3D85FC;
		}
	}
	.del {
		position: absolute;
		right: 10rpx;
		top: 50%;
		transform: translateY(-50%);
	}
}
.select-container {
	position: fixed;
	box-sizing: border-box;
	bottom: 0;
	padding: 20rpx 20rpx 40rpx 20rpx;
	width: 100vw;
	display: flex;
	align-items: center;
	background-color: #fff;
	border-top: 1px solid #E1E3E5;
	.scrollContainer {
		width: 57%;
	}
	.select-left {
		font-size: 26rpx;
		width: 25%;
	}
	.select-right {
		flex: 1;
	}
}

.select-item {
	width: 60rpx;
	height: 60rpx;
	margin-right: 6rpx;
	flex-shrink: 0;
	text {
		display: inline-block;
		width: 100%;
		height: 100;
		border-radius: 10rpx;
		color: #fff;
		font-size: 20rpx;
		text-align: center;
		line-height: 60rpx;
		background-color: #3D85FC;
	}
}
.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 32rpx;
	padding: 30rpx;
}
.popup-content {

}
</style>
